package com.lq.ecoldchain.ui.main.home

import android.arch.lifecycle.MutableLiveData
import com.alibaba.android.arouter.launcher.ARouter
import com.lq.ecoldchain.base.BaseNavigator
import com.lq.ecoldchain.base.viewmodel.BaseViewModel
import com.lq.ecoldchain.entity.OrderDetailBean
import com.lq.ecoldchain.entity.RecommendBean
import com.lq.ecoldchain.entity.RecommendOrder
import com.lq.ecoldchain.entity.TakeOrderListEntity
import com.lq.ecoldchain.internet.BaseObserver

/*
*2019/1/11 0011  14:03
*function by lq
*/
class HomeViewModel : BaseViewModel() {
    val list by lazy { ArrayList<RecommendOrder>() }
    val doing by lazy { MutableLiveData<Boolean>() }
    val haveRecommend by lazy { MutableLiveData<Boolean>() }
    val refreshing by lazy { MutableLiveData<Boolean>() }
    val adapter by lazy { HomeRecommendAdapter(list) }
    val ordering by lazy { MutableLiveData<OrderDetailBean>() }

    var page = 1
    val limit = 10

    init {
        requestData()
        orderTaking()

        adapter.setOnLoadMoreListener {
            page++
            requestData()
        }
        adapter.setOnItemChildClickListener { _, _, position ->
            ARouter.getInstance().build(BaseNavigator.prepareOrder).withString("orderId", "${list[position].id}").navigation()
        }
    }

    fun refreshData() {
        refreshing.value = true
        requestData()
        orderTaking()
    }

    private fun requestData() {
        BaseNetCore.ApiServiceImpl.orderRecommend(page, limit).compose(RxTransformer.switchSchedulers()).subscribe(object : BaseObserver<RecommendBean>() {
            override fun onSuccess(t: RecommendBean?) {
                list.clear()
                if (t != null && !t.list.isNullOrEmpty()) {
                    list.addAll(t.list)
                    haveRecommend.value = true
                    adapter.loadMoreComplete()
                    adapter.notifyDataSetChanged()
                    if (t.list.size < limit) {
                        adapter.loadMoreEnd()
                    }
                }
                refreshing.value = false
            }

            override fun onFail(code: String) {
                refreshing.value = false
            }
        })
    }

    private fun orderTaking() {
        BaseNetCore.ApiServiceImpl.orderListTaking("1", 1, 1).compose(RxTransformer.switchSchedulers()).subscribe(object : BaseObserver<TakeOrderListEntity>() {
            override fun onSuccess(t: TakeOrderListEntity?) {
                if (t != null && !t.list.isNullOrEmpty()) {
                    ordering.value = t.list[0]
                    doing.value = true
                }
            }

            override fun onFail(code: String) {}
        })
    }
}